var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

const { expressjwt } = require('express-jwt');
const md5 = require('md5');
const session = require("express-session");
const multer = require('multer');
const { ForbriddenError, ServiceError, UnknownError, UploadError } = require("./utils/errors");

require("dotenv").config();
require("express-async-errors");
require("./dao/sync");

var app = express();
const adminRouter = require("./routes/admin");
const captchaRouter = require("./routes/captcha");
const bannerRouter = require("./routes/banner");
const uploadRouter = require("./routes/upload");
const blogtypeRouter = require("./routes/blogtype");
const blogRouter = require("./routes/blog");
const demoRouter = require("./routes/demo");
const messageRouter = require("./routes/message");
const settingRouter = require("./routes/setting");
const aboutRouter = require("./routes/about");

app.use(session({
  secret: process.env.SESSION_SECRET,					// 加密和解密sessionId的秘钥
  resave: true,
  saveUninitialized: true,
  name: "sessionId"					// 设置session对应的cookie的键名称
}));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 验证token
app.use(expressjwt({
  secret: md5(process.env.JWT_SECRET),
  algorithms: ["HS256"]
}).unless({
  path: [
    { url: "/api/admin/login", methods: ["POST"] },
    { url: "/res/captcha", methods: ["GET"] },
    { url: "/api/banner", methods: ["GET"] },
    { url: "/api/blogtype", methods: ["GET"] },
    { url: "/api/blog", methods: ["GET"] },
    { url: /\/api\/blog\/\d{1,}$/, methods: ["GET"] },
    { url: "/api/project", methods: ["GET"] },
    { url: "/api/comment", methods: ["GET", "POST"] },
    { url: "/api/message", methods: ["GET", "POST"] },
    { url: "/api/about", methods: ["GET"] },
    { url: "/api/setting", methods: ["GET"] }
  ]
}));

app.use("/api/admin", adminRouter);
app.use("/res/captcha", captchaRouter);
app.use("/api/banner", bannerRouter);
app.use("/api/upload", uploadRouter);
app.use("/api/blogtype", blogtypeRouter);
app.use("/api/blog", blogRouter);
app.use("/api/project", demoRouter);
app.use("/api/comment", messageRouter);
app.use("/api/message", messageRouter);
app.use("/api/about", aboutRouter);
app.use("/api/setting", settingRouter);

// app.use((req, res, next) => {
//   next(createError(404));
// });

app.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError") {
    res.send(new ForbriddenError("未登录").toResponseJSON());
  } else if (err instanceof multer.MulterError) {
    res.send(new UploadError("文件上传失败"));
  } else if (err instanceof ServiceError) {
      res.send(err.toResponseJSON());
  } else {
    res.send(new UnknownError().toResponseJSON());
  }
});

module.exports = app;
